import Taro from "@tarojs/taro";
import setting from "./setting";
import { getToken } from "@/api/token";
import { ACCESSTOKEN } from "./constant";
import requestLoginWrapper from "./authTokenAutoRefresh";

const StatusErrorMsg = {
  // 请求体内容超出限制
  413: "文件过大",
};

const API_HOST = `${setting.host}${setting?.path || ""}`;

const interceptor = function (chain) {
  const requestParams = chain.requestParams;
  const { url, header = {} } = requestParams;

  return chain.proceed({
    ...requestParams,
    url: API_HOST + url,
    header,
  });
};

Taro.addInterceptor(interceptor);

export type TRequestOptins = {
  // 隐藏默认toast
  hiddenToast?: boolean;

  // 是否需要token
  token?: boolean;
};

export type TRequestParams = {
  url: string;
  data?: object;
  method?: "POST" | "GET";
};

export const request = (params: TRequestParams, options?: TRequestOptins) => {
  return new Promise((resolve, reject) => {
    const header = {};
    const token = getToken();

    if (token) {
      Reflect.set(header, "Authorization", `Bearer ${token}`);
    }

    Taro.request({
      ...params,
      header,
      success(res) {
        // 服务器响应
        if (res.statusCode == 200) {
          // 请求正常
          if (res.data.code == 0) {
            const result = res.data?.data;
            return resolve(result);
          }
          // 业务失败
          reject(res.data);
        }

        // 接口异常或业务失败
        return reject({ code: res.statusCode, data: res.data });
      },
      fail(serverErr) {
        reject({ code: 400, serverErr });
      },
    });
  }).catch((serverErr) => {
    console.error("request-err", serverErr, options);
    if (!options?.hiddenToast && serverErr?.msg) {
      Taro.showToast({
        icon: "none",
        title: serverErr.msg,
      });
    }

    return Promise.reject({ ...serverErr });
  });
};

// 上传文件
request.upload = (url, filePath, formData?) => {
  const token = Taro.getStorageSync(ACCESSTOKEN);

  return Taro.uploadFile({
    name: "file",
    url: API_HOST + url,
    filePath,
    formData,
    header: {
      Authorization: token ? "Bearer " + token : undefined,
    },
  })
    .then(({ statusCode, data }) => {
      console.log("Taro.uploadFile:resres", statusCode, data);

      if (statusCode == 200) {
        return JSON.parse(data).data;
      } else {
        return Promise.reject({
          statusCode,
          msg: StatusErrorMsg[413],
        });
      }
    })
    .catch((error) => {
      console.error("request-err", error);

      Taro.showToast({
        icon: "none",
        title: error.msg || "请求失败",
      });

      return Promise.reject({ error });
    });
};

export default (requestParams, requeseOptins) =>
  requestLoginWrapper(request, requestParams, requeseOptins);

// export default request

export const requestUpload = request.upload;
